﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title></title>
	<link href="js-console.css" rel="stylesheet" />
	<script src="string-extensions.js"></script>
	<!-- 8. Write a JavaScript function that replaces in a 
			HTML document given as string all the tags <a 
			href="…">…</a> with corresponding tags 
			[URL=…]…/URL]. Sample HTML fragment:
		
		<p>Please visit <a href="http://academy.telerik.com">
		our site</a> to choose a training course. Also 
		visit <a href="www.devbg.org">our forum</a> to 
		discuss the courses.</p>
		
		Result:
		<p>Please visit [URL=http://academy.telerik.com]
		our site[/URL] to choose a training course. 
		Also visit [URL=www.devbg.org]our forum[/URL] to 
		discuss the courses.</p> -->
	<style>
		textarea, button {
			display: block;
			width: 800px;
		}
	</style>
</head>
<body>
	<textarea id="input" placeholder="Enter HTML with anchor tags..."></textarea>
	<button onclick="doChange()">Replace Anchors</button>
	<div id="js-console"></div>
	<script src="js-console.js"></script>
	<script>
		function replaceAnchors(input) {
			// Replace what we can
			var res = input.replace(/<a href/gi, '[URL');
			res = res.replace(/<\/a>/gi, '[/URL]');

			// Find '>' of the anchor tag and replace it with ']'
			var index = res.indexOf('[URL=');
			var arr = new Array();
			while (index >= 0) {
				index = res.indexOf('>', index);
				
				arr.push(res.substring(0, index));
				arr.push(']');
				res = res.substr(index + 1);

				index = res.indexOf('[URL', index);
			}
			arr.push(res);

			return arr.join('');
		}

		// Button OnClick
		function doChange() {
			// Read User input
			var input = jsConsole.read("#input");

			// Output
			jsConsole.writeLine("You have entered (escaped):");
			jsConsole.writeLine("<blockquote>" + input.htmlEscape() + "</blockquote>");

			// Remove all tags
			var result = replaceAnchors(input);
			jsConsole.writeLine("Result (escaped):");
			jsConsole.writeLine("<blockquote>" + result.htmlEscape() + "</blockquote>");
		}
	</script>
</body>
</html>
